package com.nothing.thread.other;

import java.util.concurrent.Exchanger;

/**
 * 两个线程之间的数据交换
 *
 * @author haining
 */
public class ExchangerTest {


    public static void main(String[] args) throws InterruptedException {
        Exchanger exchanger = new Exchanger();

//        Thread thread = new Thread(() -> {
//            try {
//                Object data = "-公众号Java技术栈AAA";
//                System.out.println(Thread.currentThread().getName() + data);
//
//                // 开始交换数据
//                data = exchanger.exchange(data);
//                System.out.println(Thread.currentThread().getName() + data);
//            } catch (Exception e) {
//                e.printStackTrace();
//            }
//        });
//        thread.start();
//        Thread.sleep(3000L);
//        try {
//            thread.interrupt();
//        } catch (Exception e) {
//            e.printStackTrace();
//        }
//        new Thread(() -> {
//            try {
//                Object data = "-公众号Java技术栈AAA";
//                System.out.println(Thread.currentThread().getName() + data);
//
//                // 开始交换数据
//                data = exchanger.exchange(data, 3000L, TimeUnit.MILLISECONDS);
//                System.out.println(Thread.currentThread().getName() + data);
//            } catch (Exception e) {
//                e.printStackTrace();
//            }
//        }).start();
        new Thread(() -> {
            try {
                Object data = "-公众号Java技术栈AAA";
                System.out.println("s" + Thread.currentThread().getName() + data);
                while (true) {
                    // 开始交换数据
                    data = exchanger.exchange(data);
                    System.out.println(Thread.currentThread().getName() + data);
//                    Thread.sleep(3000L);
                }
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }).start();

        new Thread(() -> {
            try {
                // 开始交换数据
                Object data = "-公众号Java技术栈BBB";
                System.out.println("s" + Thread.currentThread().getName() + data);
                while (true) {
                    // 开始交换数据
                    data = exchanger.exchange(data);
                    System.out.println(Thread.currentThread().getName() + data);
//                    Thread.sleep(1000L);
                }
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }).start();
    }

}
